package com.djhu.newscollector.crawel.imp.worker;

import com.mongodb.Mongo;
import com.mongodb.MongoOptions;
import com.mongodb.ServerAddress;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.net.UnknownHostException;

/**
 * Created by zw on 2018/2/12.
 */
public class MongoService {
    private String host;
    private Integer port;
    private String db;
    private MongoTemplate mongotemplate;

    private static final String default_table = "news";

    public MongoService(String host, Integer port, String db) throws UnknownHostException {
        this.host = host;
        this.port = port;
        this.db = db;
        init();
    }


    public boolean init() throws UnknownHostException {
        MongoOptions mongoOptions = new MongoOptions();
        //mongoOptions.setSafe(true);
        ServerAddress serverAddress = new ServerAddress(host,port);
        Mongo mongo = new Mongo(serverAddress,mongoOptions);
        mongotemplate = new MongoTemplate(mongo,db);
        return true;
    }

    public synchronized void insert(Object obj){
        mongotemplate.insert(obj,default_table);
    }

}